package com.ailiwu.www.ailiwu.Fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.ailiwu.www.ailiwu.R;
import com.ailiwu.www.ailiwu.adapter.SearchCollectAdapter;
import com.ailiwu.www.ailiwu.base.BaseFragment;
import com.ailiwu.www.ailiwu.bean.SearchCollectionBean;
import com.ailiwu.www.ailiwu.url.Urls;
import com.ailiwu.www.ailiwu.utils.Logger;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:    XiYoung
 * Version    V1.0
 * Date:      2015/12/6 000622:49
 * Description:
 * Modification  History:
 * Date         	Author        		Version        	Description
 * -----------------------------------------------------------------------------------
 * 2015/12/6 0006       XiYoung              1.0                   1.0
 * Why & What is modified:
 */
public class FragmentSearchCollection extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView_hot;
    private String next_url;//上拉加载的url
    private SearchCollectAdapter mAdapter;
    private static List<SearchCollectionBean.DataEntity.PostsEntity> listData = new ArrayList<>();
    private Context mContext;

    private static final String KEY = "key";
    private static String key;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle arg = getArguments();
        if (arg != null) {
            key = arg.getString(KEY, "");
        }
    }

    public static FragmentSearchCollection newInstance(String key) {
        Bundle args = new Bundle();
        FragmentSearchCollection fragment = new FragmentSearchCollection();
        Bundle bundle = new Bundle();
        bundle.putString(KEY, key);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View inflateView() {
        View view = View.inflate(getActivity(), R.layout.fragment_hot, null);
        //获取RecyclerView
        recyclerView_hot = (RecyclerView) view.findViewById(R.id.recyclerView_hot);
        //设置网格显示,列数为2
        recyclerView_hot.setLayoutManager(new LinearLayoutManager(mAcAvtivity));
        mAdapter = new SearchCollectAdapter(getActivity(), listData);
        recyclerView_hot.setAdapter(mAdapter);
        return view;
    }

    @Override
    protected void initView(View view) {
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.mainColor);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        TextView textView = (TextView) getActivity().findViewById(R.id.btn_search);
        final EditText editText = (EditText) getActivity().findViewById(R.id.editText);
//        editText.setFocusable(false);
        editText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == 66) {
                    String string = editText.getText().toString();
                    if (string != null) {
                        key = string;
                        Updata();
                    }
                }
                return false;
            }
        });
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = editText.getText().toString();
                if (string != null) {
                    key = string;
                    Updata();
                }
            }
        });
    }

    // 加载RecyclerView数据
    @Override
    protected void initData() {
        Updata();

    }

    private void Updata() {
        // 使用xUtils的网络模块加载数据
        HttpUtils get = new HttpUtils();
        //设置连接超时时间
        get.configTimeout(100000);
        //设置缓存区中数据的存储时间，单位为毫秒,这里设置为1天.
        get.configDefaultHttpCacheExpiry(24 * 3600 * 1000);
        //设置缓存区的大小，单位是b字节
        get.configHttpCacheSize(4 * 1024 * 1024);

//        Log.i("oye", "开始加载Json");
        //开始加载数据
        get.send(HttpRequest.HttpMethod.GET, Urls.searchCollection(key), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String Json = responseInfo.result;
                if (Json != null) {
                    // 开始解析Josn字符串
                    Logger.e(Urls.searchCollection(key));
                    Logger.e("Collection====" + Json);
                    SearchCollectionBean searchCollectionBean = gson.fromJson(Json, SearchCollectionBean.class);
                    List<SearchCollectionBean.DataEntity.PostsEntity> posts = searchCollectionBean.getData().getPosts();
                    if (posts != null)
                        listData.clear();
                        listData.addAll(posts);
                }
                // 创建RecyclerView适配器,并进行设置
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.i("oye", "failure:  " + e.getMessage() + "  " + s);
            }
        });
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        }, 2000);
    }
}
